package org.example;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer {
    private final static String QUEUE_NAME = "hello";

    public static void main(String[] args) throws IOException, TimeoutException {
        //1.创建连接工厂并配置
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("localhost");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        connectionFactory.setVirtualHost("/");
        //2.通过工厂创建连接，并获取channel
        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();
        //3.创建队列
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        //4.消费消息
        //处理消息的回调
        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                System.out.println("消息是：" + new String(message.getBody()));
            }
        };

        channel.basicConsume(QUEUE_NAME, true, deliverCallback, (consumerTag -> {}));
    }

    public static void main2(String[] args) throws IOException, TimeoutException {
        //将之前的连接进行封装
        Channel channel = ConnectionUtils.getChannel();
        //创建队列
        channel.queueDeclare(Constant.QUEUE_NAME_1, false, false, false, null);
        //生产消息
        for(int i = 1; i <= 10; i++) {
            String message = i + "";
            channel.basicPublish("", Constant.QUEUE_NAME_1, null, message.getBytes());
        }
        System.out.println("====消息生产完毕===");
    }
}

